#include <iostream>
#include <unistd.h>
#include <string>
#include <cstdlib>
#include <cstring>
#include <cstdio>
 #include <sys/types.h>
#include <sys/wait.h>
#define N 2
#define NUM 1024
using namespace std;

void Writer(int wfd)
{
    string s = "hello, i am child";
    pid_t self = getpid();
    int number = 0;

    char buffer[NUM];
    while (1)
    {
        // buffer[0] = 0;
        // snprintf(buffer, sizeof(buffer), "%s-%d-%d", s.c_str(), self, number++);
        // cout << buffer << endl;
        char ch = 'c';
        write(wfd, &ch, 1);
        cout << number++ << endl;
        if (number == 5)
            break;
        // write(wfd, buffer, strlen(buffer)); // 发送给父进程
        // sleep(1);
    }
}

void Reader(int rfd)
{
    char buffer[NUM];
    while (1)
    {
        // sleep(50);
        buffer[0] = 0 ;
        ssize_t n = read(rfd, buffer, sizeof(buffer));
        if (n > 0)
        {
            buffer[n] = 0; // 0 = '\0'
            cout << "father [" << getpid() << "]" << "get a messge: "  << buffer << endl;
        }

        if (n == 0) 
        {
            cout << "read file done!" << endl;
            break;
        }
    }
}

int main()
{
    int pipefd[N] = { 0 };
    int n = pipe(pipefd);
    // cout << "pipefd[0]: " << pipefd[0] << ", pipefd[1]:"  <<  pipefd[1] << endl;

    pid_t id = fork();
    // 子进程写，父进程读
    if (id == 0) // 子进程
    {
        close(pipefd[0]);
        Writer(pipefd[1]);
        close(pipefd[1]);
        exit(0);
    }

    // 父进程
    close(pipefd[1]);
    Reader(pipefd[0]);
    pid_t rid = waitpid(id, nullptr, 0);
    
    return 0;
}
